#coding=utf8

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import Navigation, HouseType, HouseBuilding, DesignerJob, Designer, HouseStyle, Case, Banner, Article, GlobalActivity, FurnitureType, FurnitureBrand, Furniture
from django.contrib import auth
from rest_framework.decorators import api_view, detail_route, list_route, permission_classes, authentication_classes
from rest_framework.views import APIView
from helper import *
from django.utils import timezone
import datetime
from .serializers import NavigationSerializer, HouseTypeSerializer, HouseBuildingSerializer, DesignerJobSerializer, DesignerSerializer, HouseStyleSerializer, CaseSerializer, BannerSerializer, ArticleSerializer, GlobalActivitySerializer, FurnitureTypeSerializer, FurnitureBrandSerializer, FurnitureSerializer
from system.permissions import IsUserAuthenticated
from rest_framework.authtoken.models import Token
from myviewset import *
from django.db.models import Q

class NavigationViewSet(MyReadOnlyModelViewSet):
    """查询栏目"""
    #permission_classes = (IsUserAuthenticated, )
    serializer_class = NavigationSerializer

    def get_queryset(self):
        queryset = Navigation.objects.select_related("company")

        if self.request.query_params.has_key("company_id"):
            queryset = queryset.filter(company_id = self.request.query_params["company_id"])

        if self.request.query_params.has_key("parent_id"):
            queryset = queryset.filter(parent_id = self.request.query_params["parent_id"])

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter(Q(name__contains = key) | Q(id = to_UUID(key)))
        
        return queryset.all()

class HouseTypeViewSet(MyReadOnlyModelViewSet):
    """查询房屋户型"""
    serializer_class = HouseTypeSerializer

    def get_queryset(self):
        queryset = HouseType.objects

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter(Q(name__contains = key) | Q(id = to_UUID(key)))
        
        return queryset.all()


class HouseBuildingViewSet(MyReadOnlyModelViewSet):
    """查询楼盘"""
    serializer_class = HouseBuildingSerializer

    def get_queryset(self):
        queryset = HouseBuilding.objects.prefetch_related("images").select_related("region")

        if self.request.query_params.has_key("region_id"):
            queryset = queryset.filter(region_id = self.request.query_params["region_id"])

        Q_key = None
        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            Q_key = Q(addr__contains = key) | Q(description__contains = key)

        queryset = get_basecontent_queryset(queryset, self.request, Q_key)
        return queryset.all().order_by('-created_at')


class DesignerJobViewSet(MyReadOnlyModelViewSet):
    """查询设计师岗位"""
    serializer_class = DesignerJobSerializer

    def get_queryset(self):
        queryset = DesignerJob.objects

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter(Q(title__contains = key) | Q(id = to_UUID(key)))
        
        return queryset.all()

class DesignerViewSet(MyReadOnlyModelViewSet):
    """查询设计师"""
    serializer_class = DesignerSerializer

    def get_queryset(self):
        queryset = Designer.objects.select_related("job").prefetch_related("goodstyles")

        if self.request.query_params.has_key("job_id"):
            queryset = queryset.filter(job_id = self.request.query_params["job_id"])

        Q_key = None
        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            Q_key = Q(mobile = key)

        queryset = get_basecontent_queryset(queryset, self.request, Q_key)
        return queryset.all()

class HouseStyleViewSet(MyReadOnlyModelViewSet):
    """查询房屋风格"""
    serializer_class = HouseStyleSerializer

    def get_queryset(self):
        queryset = HouseStyle.objects

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter(Q(name__contains = key) | Q(id = to_UUID(key)))
        
        return queryset.all()

class CaseViewSet(MyReadOnlyModelViewSet):
    """查询案例"""
    serializer_class = CaseSerializer

    def get_queryset(self):
        queryset = Case.objects.select_related('house', 'housetype', 'housestyle', 'designer', 'house__region', 'designer__job').prefetch_related('house__images', 'designer__goodstyles')

        if self.request.query_params.has_key("house_id"):
            queryset = queryset.filter(house_id = self.request.query_params["house_id"])

        if self.request.query_params.has_key("housetype_id"):
            queryset = queryset.filter(housetype_id = self.request.query_params["housetype_id"])
    
        if self.request.query_params.has_key("housestyle_id"):
            queryset = queryset.filter(housestyle_id = self.request.query_params["housestyle_id"])

        if self.request.query_params.has_key("designer_id"):
            queryset = queryset.filter(designer_id = self.request.query_params["designer_id"])

        Q_key = None
        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            if key != "":
                likelyhouses = HouseBuilding.objects.filter(addr__contains = key).filter(isEnabled = True).values_list('id', flat=True)
                Q_key = Q(house_id__in = likelyhouses)

        queryset = get_basecontent_queryset(queryset, self.request, Q_key)
        return queryset.all().order_by('-created_at')


class BannerViewSet(MyReadOnlyModelViewSet):
    """查询banner"""
    serializer_class = BannerSerializer

    def get_queryset(self):
        queryset = Banner.objects.filter(isShow = True)

        Q_key = None

        queryset = get_basecontent_queryset(queryset, self.request, Q_key)
        return queryset.all().order_by('-created_at')


class ArticleViewSet(MyReadOnlyModelViewSet):
    """查询文章"""
    serializer_class = ArticleSerializer

    def get_queryset(self):
        queryset = Article.objects.filter(isShow = True).select_related('writor', 'reviewer')

        if self.request.query_params.has_key("writor_id"):
            queryset = queryset.filter(writor_id = self.request.query_params["writor_id"])

        if self.request.query_params.has_key("reviewer_id"):
            queryset = queryset.filter(reviewer_id = self.request.query_params["reviewer_id"])

        if self.request.query_params.has_key("review_status"):
            queryset = queryset.filter(review_status = self.request.query_params["review_status"])

        if self.request.query_params.has_key("review_time_gt"):
            """时间格式固定为：'2015-12-21 15:01:28' """
            review_time_gt = datetime.datetime.strptime(self.request.query_params["review_time_gt"], '%Y-%m-%d %H:%M:%S')
            queryset = queryset.filter(review_time__gt = review_time_gt)

        if self.request.query_params.has_key("review_time_lt"):
            """时间格式固定为：'2015-12-21 15:01:28' """
            review_time_lt = datetime.datetime.strptime(self.request.query_params["review_time_lt"], '%Y-%m-%d %H:%M:%S')
            queryset = queryset.filter(review_time__lt = review_time_lt)

        if self.request.query_params.has_key("issubmit"):
            #是否审核通过
            issubmit = self.request.query_params["issubmit"]
            if issubmit == "1":
                queryset = queryset.filter(issubmit = True)
            elif issubmit == "0":
                queryset = queryset.filter(issubmit = False)

        Q_key = None

        queryset = get_basecontent_queryset(queryset, self.request, Q_key)
        return queryset.all().order_by('-created_at')


class GlobalActivityViewSet(MyReadOnlyModelViewSet):
    """查询全局活动"""
    serializer_class = GlobalActivitySerializer

    def get_queryset(self):
        queryset = GlobalActivity.objects

        Q_key = None

        queryset = get_basecontent_queryset(queryset, self.request, Q_key)
        return queryset.all().order_by('-created_at')


class FurnitureTypeViewSet(MyReadOnlyModelViewSet):
    """查询家具类型"""
    serializer_class = FurnitureTypeSerializer

    def get_queryset(self):
        queryset = FurnitureType.objects

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter(Q(name__contains = key) | Q(id = to_UUID(key)))
        
        return queryset.all()

class FurnitureBrandViewSet(MyReadOnlyModelViewSet):
    """查询家具品牌"""
    serializer_class = FurnitureBrandSerializer

    def get_queryset(self):
        queryset = FurnitureBrand.objects

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter(Q(name__contains = key) | Q(id = to_UUID(key)))
        
        return queryset.all()


class FurnitureViewSet(MyReadOnlyModelViewSet):
    """查询家具"""
    serializer_class = FurnitureSerializer

    def get_queryset(self):
        queryset = Furniture.objects.select_related('ftype', 'brand').prefetch_related('images')

        if self.request.query_params.has_key("type_id"):
            queryset = queryset.filter(ftype_id = self.request.query_params["type_id"])

        if self.request.query_params.has_key("brand_id"):
            queryset = queryset.filter(brand_id = self.request.query_params["brand_id"])

        Q_key = None
        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            if key != "":
                Q_key = Q(model__contains = key) | Q(spec__contains = key)

        queryset = get_basecontent_queryset(queryset, self.request, Q_key)
        return queryset.all().order_by('-created_at')